/**
 * 
 */
package br.com.skynix.tcmc.converter;

import java.lang.reflect.InvocationTargetException;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import br.com.skynix.tcmc.base.model.EntidadeAuditavel;
import br.com.skynix.tcmc.base.spring.IServiceAuditavel;
import br.com.skynix.tcmc.util.WebUtil;

/**
 * @author mgrb
 * 
 */
public abstract class AbstractEntidadeAuditavelConverter<T extends EntidadeAuditavel>
		implements Converter {

	private static Logger LOGGER = Logger
			.getLogger(AbstractEntidadeAuditavelConverter.class);

	protected abstract IServiceAuditavel<T> getService();

	protected String getPropriedade() {
		return "id";
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.faces.convert.Converter#getAsObject(javax.faces.context.FacesContext
	 * , javax.faces.component.UIComponent, java.lang.String)
	 */
	@Override
	public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) {
		if (StringUtils.isNotBlank(arg2)) {
			return getService().buscarPelaChave(Long.valueOf(arg2));
		}
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.faces.convert.Converter#getAsString(javax.faces.context.FacesContext
	 * , javax.faces.component.UIComponent, java.lang.Object)
	 */
	@Override
	public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) {
		if (arg2 != null) {
			try {
				return BeanUtils.getProperty(arg2, getPropriedade());
			}
			catch (IllegalAccessException exception) {
				String mensage = WebUtil
						.getMensage("geral.converter.fatalError");
				arg0.addMessage(null,
						new FacesMessage(FacesMessage.SEVERITY_FATAL, mensage,
								exception.getLocalizedMessage()));
				LOGGER.fatal(mensage, exception);
			}
			catch (InvocationTargetException exception) {
				String mensage = WebUtil
						.getMensage("geral.converter.fatalError");
				arg0.addMessage(null,
						new FacesMessage(FacesMessage.SEVERITY_FATAL, mensage,
								exception.getLocalizedMessage()));
				LOGGER.fatal(mensage, exception);
			}
			catch (NoSuchMethodException exception) {
				String mensage = WebUtil
						.getMensage("geral.converter.fatalError");
				arg0.addMessage(null,
						new FacesMessage(FacesMessage.SEVERITY_FATAL, mensage,
								exception.getLocalizedMessage()));
				LOGGER.fatal(mensage, exception);
			}
		}
		return null;
	}

}
